package demo3;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-07-31
 * Time: 14:49
 */
public class TestDemo4 {

    /**
     * 每个线程循环 1w 次，累加变量 count 的值，count 默认值为 0，注意线程安全问题
     */
    static class Counter{
        public int count = 0;
        public synchronized void increase(){
            count++;
        }
    }

    public static void main(String[] args) {
        Counter counter = new Counter();;
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; ++i) {
                counter.increase();
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10000; ++i) {
                counter.increase();
            }
        });
        t2.start();
        try {
            t2.join();
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(counter.count);
    }



}
